<script setup lang="ts">
import { ref, computed, watch, onUnmounted } from 'vue'
import submitSuccessImg from "#/assets/images/pay/sumbit_success.png"
import scanCodeImg from "#/assets/images/pay/scan.png"
import weixinPayImg from "#/assets/images/pay/weixin_pay.png"
import QrCodeImage from './qr-code-image.vue'
import { type PayStep, type OrderInfo } from './const'
import { getNativeCodeApi, getPayResultApi } from '#/api/lesson/pay'

defineOptions({ name: 'PayOrder' })

const emit = defineEmits(['nextStep'])
const props = defineProps<{
  steps: PayStep,
  orderInfo: OrderInfo,
  visible:Boolean
}>()

// 传入二维码组件的字符串，可按需替换为实际支付链接
const payCodeText = ref(``)
const payResult = ref(``)
// 二维码过期状态
const isQrCodeExpired = ref(false)
const payLoading = ref(false)
// 轮询相关
const pollDuration = 120 // 轮询时长（秒）
const pollInterval = 3000 // 轮询间隔（毫秒）
let pollTimer: ReturnType<typeof setInterval> | null = null
let pollStartTime: number | null = null

// 倒计时相关
const countdown = ref(pollDuration) // 倒计时初始值
let countdownTimer: ReturnType<typeof setInterval> | null = null

// 开始倒计时
const startCountdown = () => {
  stopCountdown() // 防止重复启动
  countdown.value = pollDuration
  countdownTimer = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--
    } else {
      stopCountdown()
    }
  }, 1000)
}

// 停止倒计时
const stopCountdown = () => {
  if (countdownTimer) {
    clearInterval(countdownTimer)
    countdownTimer = null
  }
}

// 重置倒计时
const resetCountdown = () => {
  stopCountdown()
  countdown.value = pollDuration
}

// 刷新二维码
const refreshQrCode = () => {
  isQrCodeExpired.value = false
  payCodeText.value = ``
  payResult.value = ``
  resetCountdown()
  getNativeCode()
}

// 支付方式列表 - 改为响应式数据
const payList = ref([
  {
    name: '微信支付',
    img: weixinPayImg,
    checked: true
  }
])

// 切换支付方式
const switchPaymentMethod = (index: number) => {
  // 将所有支付方式设置为未选中
  payList.value.forEach((item, i) => {
    item.checked = i === index
  })
}

// 获取当前选中的支付方式
const currentPaymentMethod = computed(() => {
  return payList.value.find(item => item.checked)
})

const getNativeCode = () => {
  if (!props.orderInfo.orderId) return
  payLoading.value = true
  getNativeCodeApi(props.orderInfo.orderId as string).then(res => {
    payCodeText.value = res.codeUrl
    payLoading.value = false
  }).catch((err) => {
    console.log(err)
    payLoading.value = false
    payResult.value = '获取二维码失败'
    emit('nextStep', "0")
  })
}

watch(() => props.orderInfo.orderId, () => {
  getNativeCode()
}, { deep: true, immediate: true })

const getPayResult = () => {
  getPayResultApi(props.orderInfo.orderId as string).then(res => {
    const { shouldStopPolling, bizStatus, content } = res;
    // emit('nextStep', 'success')
    if (shouldStopPolling) {
      stopPollingPayResult()
      if (bizStatus === 'pay_success') {
        emit('nextStep')
      } else {
        refreshQrCode()
        payResult.value = content
      }
    }
  }).catch(() => {
    stopPollingPayResult()
    payLoading.value = false
  })
}


const startPollingPayResult = () => {
  stopPollingPayResult() // 防止重复轮询
  pollStartTime = Date.now()
  startCountdown() // 启动倒计时
  pollTimer = setInterval(() => {
    const elapsed = (Date.now() - (pollStartTime as number)) / 1000
    if (elapsed >= pollDuration || !props.visible) {
      stopPollingPayResult()
      refreshQrCode()
      return
    }
    getPayResult()
  }, pollInterval)
}

const stopPollingPayResult = () => {
  if (pollTimer) {
    clearInterval(pollTimer)
    pollTimer = null
    pollStartTime = null
  }
  stopCountdown() // 停止倒计时
}

// 在二维码生成后开始轮询
watch(() => payCodeText.value, (val) => {
  if (val) {
    startPollingPayResult()
  } else {
    stopPollingPayResult()
  }
})

// 组件卸载时清理轮询
onUnmounted(() => {
  stopPollingPayResult()
  stopCountdown()
})

// 暴露 stopPollingPayResult 方法
defineExpose({
  stopPollingPayResult
})


</script>
<template>
  <div class="pt-6 bg-white rounded">
    <!-- 左右布局容器 -->
    <div class="flex items-end  justify-between">
      <!-- 左侧：成功图标和提示信息 -->
      <div class="flex items-center gap-4">
        <!-- 成功图标 -->
        <img :src="submitSuccessImg" alt="success" class="w-25 h-25 object-contain flex-shrink-0" />
        <!-- 文字信息 -->
        <div class="flex flex-col gap-2">
          <h3 class="text-[#30a46c] text-xl font-medium">订单提交成功，请尽快付款</h3>
          <p class="text-sm text-[#191919] m-0">
            请您在<span class="text-[#e5484d] font-medium">120分钟</span>内完成支付，逾期未支付订单将自动取消。
          </p>
          <!-- 订单号 -->
          <p class="text-sm text-[#aeaeae] m-0">
            订单号 {{ orderInfo.orderNo }}
          </p>
        </div>
      </div>

      <!-- 右侧：订单金额 -->
      <div class="flex items-baseline gap-1 flex-shrink-0 pb-2">
        <span class="text-[#191919] text-sm mr-2">订单金额</span>
        <span class="text-3xl font-medium text-[#e5484d]">{{ orderInfo.amount }}</span>
        <span class="text-[#e5484d] text-sm">元</span>
      </div>
    </div>
    <!-- 支付方式与二维码区域 -->
    <div class="rounded p-6 bg-[#f2f7fd] pt-4 mt-2">
      <!-- 支付方式头部 -->
      <div class="flex items-center gap-4">
        <span class="text-[#595959]">支付方式</span>
        <!-- 支付方式选择框 - 使用v-for遍历 -->
        <div v-for="(item, index) in payList" :key="index" class="relative overflow-hidden cursor-pointer"
          style="width: 200px;" @click="switchPaymentMethod(index)">
          <div class="flex items-center gap-3 px-4 py-2 bg-white border rounded-lg transition-all duration-200"
            :class="item.checked ? 'border-[#2a67f1]' : ' border-[#e5e7eb] hover:border-[#2a67f1]'">
            <!-- 支付图标 -->
            <img v-if="item.img" :src="item.img" :alt="item.name" class="w-6 h-6 object-contain flex-shrink-0" />
            <!-- 支付方式文字 -->
            <span class="text-[#191919] text-sm">{{ item.name }}</span>
          </div>
          <!-- 右上角三角形勾选 - 只在选中时显示 -->
          <div v-if="item.checked" class="corner-triangle">
            <span class="check-mark">✓</span>
          </div>
        </div>
      </div>
      <div class="h-px bg-[#e6eefb] my-4"></div>
      <!-- 二维码与说明 -->
      <div class="flex items-center justify-center gap-10">
        <!-- 二维码容器 -->
        <div class="relative">
          <QrCodeImage :text="payCodeText" :size="180" />
          <div v-if="payLoading" class="h-[180px] w-[180px] flex items-center justify-center qr-expired-overlay">
            <div class="text-sm text-white">二维码生成中...</div>
          </div>
          <!-- 过期蒙层 -->
          <!-- <div v-if="isQrCodeExpired" class="qr-expired-overlay">
            <div class="expired-content">
              <div class="text-white text-sm mb-3">二维码已过期</div>
              <el-button type="primary" @click="refreshQrCode">刷新</el-button>
            </div>
          </div> -->
        </div>
        <div class="space-y-4">
          <div class="flex items-center gap-3">
            <img :src="scanCodeImg" alt="scanCode" class="w-11 h-11 object-contain flex-shrink-0" />
            <div>
              <p class="text-sm text-[#595959]">请使用{{ currentPaymentMethod?.name }}扫一扫</p>
              <p class="text-sm text-[#595959]">扫描二维码支付</p>
            </div>
          </div>
          <p class="font-medium text-lg">请在<span class="text-[#e5484d] inline-block text-center w-10">{{countdown}}S</span>内完成扫码支付</p>
          <p class="text-[#6b7280] m-0">如扫码失败，请
            <button type="button" class="text-[#2a67f1]" @click.stop="refreshQrCode">刷新二维码</button>
          </p>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 右上角三角形勾选样式 */
.corner-triangle {
  position: absolute;
  top: 0;
  right: 0;
  width: 0;
  height: 0;
  border-top: 20px solid #2a67f1;
  border-left: 20px solid transparent;
  border-top-right-radius: 8px;
}

/* 白色小勾样式 */
.check-mark {
  position: absolute;
  top: -17px;
  right: 3px;
  color: white;
  font-size: 8px;
  font-weight: bold;
  z-index: 20;
  line-height: 1;
}

/* 二维码过期蒙层 */
.qr-expired-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
}

/* 过期内容 */
.expired-content {
  text-align: center;
}
</style>
